"""
逻辑接口层
    购物商城的接口
"""
from interface import bank_interface
from db import db_handler
from lib import common
#产生一个日志对象
logginger = common.get_log("shop")

#购物车支付功能功能
def pay(loginer,shop_car):   #{"小滑头":[5,10个]}
    zongjia = 0
    names = ""
    for name,num_price in shop_car.items():
        num,price=num_price
        names+=f"{name}{num}个,"
        zongjia += num*price
    names = names.strip(",")
    flag,msg = bank_interface.pay_car(loginer,zongjia,names)
    logginger.info(msg)
    if flag:
        return True,msg
    return False,msg

#购物车保存功能
def save(loginer,shop_car): #{"小滑头":[5,10个]}
    user_dic = db_handler.select(loginer)
    shop_car1 = user_dic["shop_car"]
    if not shop_car1:
        for name,num_price in shop_car.items():
            shop_car1[name] = num_price
        db_handler.save(user_dic)
        msg = "保存购物车成功！"
        logginger.info(msg)
        return True,msg
    
    else:
        for name,num_price in shop_car.items():
            if name in shop_car1:
                shop_car1[name][1]+=num_price[1]
            else:
                shop_car1[name] = num_price
        db_handler.save(user_dic)
        msg = "保存购物车成功！"
        logginger.info(msg)
        return True,msg                
#查询购物车功能
def select_car(loginer):
    user_dic = db_handler.select(loginer)
    shop_car = user_dic["shop_car"]
    if shop_car:
        return True,shop_car
    return False,f"用户{loginer}购物车中没有商品！"